package xyz.xiezc.spider.business;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.setting.Setting;
import lombok.extern.slf4j.Slf4j;
import xyz.xiezc.ioc.annotation.Component;
import xyz.xiezc.ioc.annotation.InitMethod;
import xyz.xiezc.ioc.annotation.Inject;
import xyz.xiezc.spider.common.XBean;
import xyz.xiezc.spider.entity.MzituBean;
import xyz.xiezc.spider.entity.MzituImgBean;
import xyz.xiezc.spider.upload.OssClient;

import java.io.File;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author wb-xzc291800
 * @date 2019/04/09 14:22
 */
@Component
@Slf4j
public class BusinessImpl implements Business {


    @Inject
    Setting setting;

    @Inject
    OssClient ossClient;

    private String imgDir;

    @InitMethod
    public void init() {
        imgDir = setting.getStr("data.dir");
    }

    @Override
    public XBean save(XBean xBean) throws SQLException {
        List bean = xBean.getBean();
        if (bean == null || bean.isEmpty()) {
            return xBean;
        }
        for (Object baseDO : bean) {
            if (baseDO instanceof MzituBean) {
                saveMzituBean(xBean, (MzituBean) baseDO);
            } else if (baseDO instanceof MzituImgBean) {
                MzituImgBean mzituImgBean = (MzituImgBean) baseDO;
                saveMzituImgBean(xBean, mzituImgBean);
            }
        }
        return xBean;
    }

    /**
     * 保存图集对象
     *
     * @param xBean
     * @param baseDO
     * @return
     * @throws SQLException
     */
    private void saveMzituBean(XBean xBean, MzituBean baseDO) throws SQLException {
        MzituBean mzituBean = baseDO;
        String title = mzituBean.getTitle();
        if (StrUtil.isBlank(title)) {
            return;
        }
        Entity entity = Entity.create("xs_photo_album");
        entity.set("title", mzituBean.getTitle());
        entity.set("create_time", LocalDateTime.now());
        entity.set("fetch_url", mzituBean.getFetchUrl());
        if (mzituBean.getType() != null) {
            entity.set("type", mzituBean.getType());
        }
        if (mzituBean.getPublishTime() != null) {
            entity.set("publish_time", mzituBean.getPublishTime());
        }
        Entity existEntity = Db.use().get(entity.filter("title", "fetch_url"));
        if (existEntity == null) {
            Long id = Db.use().insertForGeneratedKey(entity);
            xBean.getRequest().addExtra("albumId", id);
        } else {
            Db.use().update(entity, existEntity);
            long id = existEntity.getInt("id");
            xBean.getRequest().addExtra("albumId", id);
        }
        log.info("save MzituBean success; url:{}", xBean.getRequest().getUrl());
        return;
    }

    /**
     * 保存图片对象
     *
     * @param xBean
     * @param baseDO
     * @throws SQLException
     */
    private void saveMzituImgBean(XBean xBean, MzituImgBean baseDO) throws SQLException {
        MzituImgBean mzituImgBean = baseDO;
        if (StrUtil.isBlank(mzituImgBean.getPath())) {
            return;
        }
        if (mzituImgBean.getPath().startsWith("/")) {
            mzituImgBean.setPath(mzituImgBean.getPath().substring(1));
        }

        insertTag(xBean, mzituImgBean);
        insertMzituImg(xBean, mzituImgBean);
    }


    private void insertMzituImg(XBean xBean, MzituImgBean mzituImgBean) throws SQLException {
        Object exist = xBean.getOther("exist");
        Entity entity = createMzituBeanEntity(mzituImgBean);
        if (exist == null || !(boolean) exist) {
            Long aLong = Db.use().insertForGeneratedKey(entity);
            upOssImg(mzituImgBean.getPath(), aLong);
            log.info("save MzituImgBean success; url:{}", xBean.getRequest().getUrl());
        } else {
            Db.use().insertOrUpdate(entity, "path");
        }
    }

    private Entity createMzituBeanEntity(MzituImgBean mzituImgBean) {
        Entity entity = Entity.create("xs_photo")
                .set("path", mzituImgBean.getPath())
                .set("size", mzituImgBean.getSize())
                .set("fetch_url", mzituImgBean.getFetchUrl())
                .set("create_time", LocalDateTime.now());
        if (mzituImgBean.getTitle() == null) {
            entity.set("title", mzituImgBean.getTitle());
        }
        if (mzituImgBean.getShowTime() == null) {
            entity.set("show_time", mzituImgBean.getShowTime());
        }
        if (mzituImgBean.getType() == null) {
            entity.set("type", mzituImgBean.getType());
        }
        if (mzituImgBean.getAlbumId() == null) {
            entity.set("album_id", mzituImgBean.getAlbumId());
        }
        return entity;
    }

    private void insertTag(XBean xBean, MzituImgBean mzituImgBean) throws SQLException {
        List<String> tags = (List<String>) xBean.getRequest().getExtra().get("tags");
        if (tags != null) {
            for (String tag : tags) {
                Entity entity = Entity.create("xs_tag")
                        .set("album_id", mzituImgBean.getAlbumId())
                        .set("name", tag)
                        .set("create_time", LocalDateTime.now());
                Entity filter = entity.filter("album_id", "name");
                int count = Db.use().count(filter);
                if (count == 0) {
                    Db.use().insert(entity);
                }
            }
        }
    }

    private void upOssImg(String path, final Long aLong) {
        //上传OSS
        ThreadUtil.execute(() -> {
            try {
                ossClient.upObject(path, new File(imgDir + path));
                Db.use().update(Entity.create().set("have_up", 1),
                        Entity.create("xs_photo").set("id", aLong));
                log.info("上传OSS成功, img_path :{}", path);
            } catch (Exception e) {
                log.error("上传OSS错误, 图片id: {}", aLong);
                log.error("", e);
            }
        });
    }
}
